package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import jakarta.annotation.PostConstruct;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcMessageOut;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 设备离线处理器
 * @author hehuaiping
 */
@Slf4j
@Component
@AllArgsConstructor
@ChannelHandler.Sharable
public class YkcDeviceDisconnectHandler extends YkcAbstractHandler<Void, YkcMessageOut>{
    // private final DeviceEventComponent deviceEventComponent;

    @PostConstruct
    public void init() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::shutdownHooks));
    }

    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        /*DeviceRespOfflineDTO offlineDTO = new DeviceRespOfflineDTO(
                channel.channel().attr(ChannelAttributeKeyConstants.CHANNEL_ATTR_DEVICE_NO).get(), LocalDateTime.now());
        deviceEventComponent.broadcastDeviceOfflineReport(offlineDTO);
        log.info("device disconnect: {}", offlineDTO);*/
        removeChannel(channel);
    }

    @Override
    public void write(ByteBuf byteBuf, YkcMessageOut out) {

    }

    private void shutdownHooks() {
       /* CHANNEL_CONTEXT_MAP.forEach((deviceNo, channel) -> {
            DeviceRespOfflineDTO offlineDTO = new DeviceRespOfflineDTO(deviceNo, LocalDateTime.now());
            deviceEventComponent.broadcastDeviceOfflineReport(offlineDTO);
            log.info("jvm shutdown hooks device disconnect: {}", offlineDTO);
        });*/
    }

}
